<?php

namespace addons\shopro\job;

use addons\shopro\service\commission\Agent as AgentService;
use app\admin\model\shopro\commission\Agent;
use app\admin\model\shopro\commission\MonthlyCompliance;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\Performance;
use app\admin\model\shopro\user\User;
use fast\Random;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\queue\Job;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 月度达标奖
 */
class Monthly extends BaseJob
{

    /**
     * 分红接力赛
     */
    public function index(Job $job, $payload)
    {
        try {
            Db::transaction(function () {
                $this->monthly();
            });
            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            $job->delete();
            format_log_error($e, 'RechargeCorrect.HttpResponseException', $message);
        } catch (\Exception $e) {
            format_log_error($e, 'RechargeCorrect');
        }
    }

    public function level(Job $job, $data)
    {
        try {
            $id = $data["user_id"];
            /*$model=new  \app\admin\model\User();
            $user =$model->where("id",$id)->find();
            $agent = new AgentService($user);
            $agent->runAgentUpgradePlan(true,0);*/
            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            format_log_error($e, 'RechargeCorrect.HttpResponseException', $message);
        } catch (\Exception $e) {
            format_log_error($e, 'RechargeCorrect');
        }
    }

    public function monthly()
    {
        $configs = ShoproConfig::getConfigs('shop.bonus.bonus_monthly', false);//月度达标奖配置
        $day = strtotime(date("Y-m", strtotime("-1 day", (time() - 6))));
        $year = date("Y", strtotime("-1 months", time()));
        $month = date("m", strtotime("-1 months", time()));
        $user = Agent::where("level >=" . $configs["level"])
            ->column("user_id");
        $monthly_data = [];
        $time = time();
        $compliance = [];
        foreach ($configs["compliance"] as $vss) {
            $compliance[$vss["money"]] = $vss["gift"];
        }

        $userPrizeMoney = [];//已发奖励对应的用户
        if (!empty($user)) {
            $userPerformance = [];
            foreach ($user as $v) {
                $userPerformance[$v] = Performance::where(["user_id" => $v])
                    ->whereTime("createtime", "last month")
                    ->where("level >= " . $configs["level"])->sum("money");//业绩
            }
            asort($userPerformance);
            foreach ($userPerformance as $user_id => $performance) {
                if ($performance > 0) {
                    krsort($compliance);
                    $rate = $this->pink($compliance, $performance);
                    if ($rate > 0) {
                        $performance_max = 0;//大市场业绩
                        $performance_min = 0;//小市场业绩
                        $subordinates = User::where(["parent_user_id" => $user_id])->select();
                        $money = bcmul($performance, ($rate / 100), 2);
                        if (!empty($subordinates)) {
                            $childIds = $this->getChildIds($user_id);//用户获取所有下级id

                            $childMonthly = $this->getChildMonthly($childIds, $userPrizeMoney, $user);//获取所有下级中已经发放的达标奖

                            //查找下级的业绩
                            foreach ($subordinates as $subordinate) {
                                $subordinate_performance_calc = Performance::where(["user_id" => $subordinate["id"]])
                                    ->whereTime("createtime", "last month")
                                    /*->where("level >= " . $configs["level"])*/ ->sum("money");//业绩=>只用作计算大小市场
                                //获取大市场业绩
                                if ($performance_max < $subordinate_performance_calc) {
                                    $performance_max = $subordinate_performance_calc;
                                }
                            }
                            $performance_min = $performance - $performance_max;//计算小市场业绩
                            $money = bcsub($money, $childMonthly, 2);
                            $userPrizeMoney[$user_id] = $money;
                            $monthly_data[] = [
                                "user_id" => $user_id,
                                "performance" => $performance,//业绩
                                "rate" => $rate,//分红比例
                                "rate_setting" => json_encode($configs),//分红设置
                                "createtime" => $time,
                                "day_time" => $day,
                                "money" => $money,
                                "year" => $year,//年
                                "month" => $month,//月
                                "performance_max" => $performance_max,//大市场业绩
                                "performance_min" => $performance_min,//小市场业绩
                            ];
                        } else {
                            $monthly_data[] = [
                                "user_id" => $user_id,
                                "performance" => $performance,//业绩
                                "rate" => $rate,//分红比例
                                "rate_setting" => json_encode($configs),//分红设置
                                "createtime" => $time,
                                "day_time" => $day,
                                "money" => $money,
                                "year" => $year,//年
                                "month" => $month,//月
                                "performance_max" => $performance_max,//大市场业绩
                                "performance_min" => $performance_min,//小市场业绩
                            ];
                        }
                    }
                }
            }
            if (!empty($monthly_data)) {
                $model = new MonthlyCompliance();
                $model->saveAll($monthly_data);
            }
        }
    }

    /**
     * @param array $childIds
     * 通过下级ID获取所有已发业绩达标奖
     */
    private function getChildMonthly($childIds = [], $userPrizeMoney, $agentIds)
    {
        $subordinate_performance_all = 0;//下级已发达标奖金额
        // dump(json_encode($userPrizeMoney)."--下级金额");
        if ($childIds && $userPrizeMoney) {
            foreach ($childIds as $id) {
                //计算下级的金额
                $subordinate_performance_all += isset($userPrizeMoney[$id]) ? $userPrizeMoney[$id] : 0;
            }
        }
        return $subordinate_performance_all;
    }

    /**
     * @param $user_id
     * @return array
     * 获取所有下级用户id数组
     */
    private function getChildIds($user_id)
    {
        $childsArr = User::where(["parent_user_id" => $user_id])->column("id");
        if ($childsArr) {
            foreach ($childsArr as $v) {
                $arr = $this->getChildIds($v);
                if ($arr) $childsArr = array_merge($childsArr, $arr);
            }
        }
        return $childsArr;
    }

    private function pink($compliance, $performance)
    {
        $rate = 0;
        foreach ($compliance as $ks => $vs) {
            if ($ks <= $performance) {
                $rate = $vs;
                break;
            }
        }
        return $rate;
    }
}
